<?php
class Controller_Online_EbayListing extends Controller_Abstract
{
	function actionCreate()
	{
		$this->_view['title'] = '创建';
		$this->_view['shop'] = Shop_User_Mapping::getShopByPlatform();
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->order('sort')->asArray()->getAll();
		$this->_view['country'] = Country::find()->asArray()->getAll();
	}
	
	function actionCreateSave()
	{
		$this->_view['title'] = '创建（保存）';
		if ($this->_context->isPOST())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$listing = Online_Ebay_Listing::assembleListingByPost($_POST);
				$create_result = Online_Ebay_Listing::create($listing);
				return $this->_redirectMessage('', $create_result['message'], url('Online::EbayListing/LibraryList'), $create_result['ack']);
			}
			else
			{
				return $this->_redirectMessage('创建失败', $mapping['message'], $_SERVER['HTTP_REFERER'], $mapping['ack']);
			}
		}
	}
	
	function actionEdit()
	{
		$this->_view['title'] = '编辑';
		Online_Ebay_Listing::updateListing($_GET['id']);
		$this->_view['shop'] = Shop_User_Mapping::getShopByPlatform();
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->order('sort')->asArray()->getAll();
		$listing = Online_Ebay_Listing::find('id=?', $_GET['id'])->asArray()->getOne();
		if ($listing['lib_flag'] == Q::ini('custom_flag/ebay_listing_lib_flag/flag/value'))
		{
			$this->_view['is_folder'] = 1;
		}
		if ($listing['variation'] != Q::ini('custom_flag/online_ebay_listing_variation/variation/value') && $listing['listing_type'] == Q::ini('custom_flag/online_ebay_listing_type/chinese/value'))
		{
			$listing_type = 'Chinese';
		}
		if ($listing['variation'] != Q::ini('custom_flag/online_ebay_listing_variation/variation/value') && ($listing['listing_type'] == Q::ini('custom_flag/online_ebay_listing_type/fixedpriceitem/value') || $listing['listing_type'] == Q::ini('custom_flag/online_ebay_listing_type/personalOffer/value')))
		{
			$listing_type = 'FixedPriceItem';
		}
		if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
		{
			$listing_type = 'MultiSKU';
		}
		if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
		{
			$item = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing['id'])->asArray()->getAll();
		}
		else
		{
			$item = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing['id'])->asArray()->getOne();
		}
		$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
		$store_categories = Online_Ebay_Listing::getStoreCategories($listing['shop_id'], $site_id);
		$features = Online_Ebay_Listing::getCategoryFeatures($listing['shop_id'], $site_id, $listing['primary_category']);
		$specifics = Online_Ebay_Listing::getCategorySpecifics($listing['shop_id'], $site_id, $listing['primary_category']);
		$item_specifics = Online_Ebay_Listing_Specifics::getListingSpecifics($listing['id'], $specifics['specifics']);
		if ($listing_type == 'MultiSKU')
		{
			$variation_specifics = Online_Ebay_Listing_Specifics::getVariationsSpecifics($item, $specifics['specifics']);
			$this->_view['variation_specifics'] = $variation_specifics;
		}
		if ($listing['schedule_flag'] != Q::ini('custom_flag/online_ebay_listing_schedule_flag/not_set/value'))
		{
			preg_match_all('#(\d{4}-\d{2}-\d{2})\s(\d{2}):(\d{2})#', $listing['schedule_next_time'], $schedule_time_array);
			$listing['schedule_date'] = $schedule_time_array[1][0];
			$listing['schedule_hour'] = $schedule_time_array[2][0];
			$listing['schedule_minute'] = $schedule_time_array[3][0];
		}
		$listing['primary_category_name'] = ($listing['primary_category'] ? Online_Ebay_Listing_Categories::getCategoryName($listing['primary_category'], $listing['site']) : '');
		$listing['second_category_name'] = ($listing['second_category'] ? Online_Ebay_Listing_Categories::getCategoryName($listing['second_category'], $listing['site']) : '');
		Online_Ebay_Listing_Extend::getListingExtend($listing);
		$pictures = Online_Ebay_Listing_Picture::getListingPicture($listing['id']);
		$details = Online_Ebay_Listing::getEbyDetails($site_id);
		$this->_view['country'] = Country::find()->asArray()->getAll();
		$this->_view['listing'] = $listing;
		$this->_view['currency'] = Currency::find('id=?', $listing['currency_id'])->asArray()->getOne();;
		$this->_view['listing_type'] = $listing_type;
		$this->_view['store_categories'] = $store_categories['categories'];
		$this->_view['features'] = $features['features'];
		$this->_view['specifics'] = $specifics['specifics'];
		$this->_view['item_specifics'] = $item_specifics;
		$this->_view['item'] = $item;
		$this->_view['pictures'] = $pictures;
		$this->_view['dispatch'] = $details['details']['dispatch'];
		$this->_view['shipping_service'] = $details['details']['shipping_service'];
		$this->_view['listing_shipping'] = Online_Ebay_Listing_Shipping::getListingShipping($listing['id']);
		$this->_view['shipping_location'] = $details['details']['shipping_location'];
		$this->_view['shipping_location_json'] = json_encode($details['details']['shipping_location']);
		$this->_view['return_policy'] = $details['details']['return_policy'];
		if (isset($listing['item_id']) && $listing['item_id'])
		{
			$this->_view['not_schedule_time'] = 'not_schedule_time';
		}
	}
	
	function actionEditSave()
	{
		$this->_view['title'] = '编辑（保存）';
		if ($this->_context->isPOST())
		{
			$listing_in_db = Online_Ebay_Listing::find('id=?', $_POST['id'])->asArray()->getOne();
			if ($listing_in_db)
			{
				$mapping = Shop_User_Mapping::checkMapping($listing_in_db['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					$listing = Online_Ebay_Listing::assembleListingByPost($_POST);
					$edit_result = Online_Ebay_Listing::edit($listing);
					return $this->_redirectMessage('', $edit_result['message'], $_SERVER['HTTP_REFERER'], $edit_result['ack']);
				}
				else
				{
					return $this->_redirectMessage('编辑失败', $mapping['message'], $_SERVER['HTTP_REFERER'], $mapping['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('编辑失败', '该listing不存在', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionCopy()
	{
		$this->_view['title'] = '复制';
		Online_Ebay_Listing::updateListing($_GET['id']);
		$shop = Shop_User_Mapping::getShopByPlatform();
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->order('sort')->asArray()->getAll();
		$listing = Online_Ebay_Listing::find('id=?', $_GET['id'])->asArray()->getOne();
		$include_shop = false;
		foreach ($shop as $s)
		{
			if ($s['id'] == $listing['shop_id'])
			{
				$include_shop = true;
			}
		}
		if ( ! $include_shop)
		{
			$current_shop = Shop::find('id=?', $listing['shop_id'])->asArray()->getOne();
			array_unshift($shop, $current_shop);
		}
		$this->_view['shop'] = $shop;
		if ($listing['variation'] != Q::ini('custom_flag/online_ebay_listing_variation/variation/value') && $listing['listing_type'] == Q::ini('custom_flag/online_ebay_listing_type/chinese/value'))
		{
			$listing_type = 'Chinese';
		}
		if ($listing['variation'] != Q::ini('custom_flag/online_ebay_listing_variation/variation/value') && ($listing['listing_type'] == Q::ini('custom_flag/online_ebay_listing_type/fixedpriceitem/value') || $listing['listing_type'] == Q::ini('custom_flag/online_ebay_listings_type/personalOffer/value')))
		{
			$listing_type = 'FixedPriceItem';
		}
		if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
		{
			$listing_type = 'MultiSKU';
		}
		if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
		{
			$item = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing['id'])->asArray()->getAll();
		}
		else
		{
			$item = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing['id'])->asArray()->getOne();
		}
		$listing['primary_category_name'] = ($listing['primary_category'] ? Online_Ebay_Listing_Categories::getCategoryName($listing['primary_category'], $listing['site']) : '');
		$listing['second_category_name'] = ($listing['second_category'] ? Online_Ebay_Listing_Categories::getCategoryName($listing['second_category'], $listing['site']) : '');
		Online_Ebay_Listing_Extend::getListingExtend($listing);
		$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
		$store_categories = Online_Ebay_Listing::getStoreCategories($listing['shop_id'], $site_id);
		$features = Online_Ebay_Listing::getCategoryFeatures($listing['shop_id'], $site_id, $listing['primary_category']);
		$specifics = Online_Ebay_Listing::getCategorySpecifics($listing['shop_id'], $site_id, $listing['primary_category']);
		$item_specifics = Online_Ebay_Listing_Specifics::getListingSpecifics($listing['id'], $specifics['specifics']);
		if ($listing_type == 'MultiSKU')
		{
			$variation_specifics = Online_Ebay_Listing_Specifics::getVariationsSpecifics($item, $specifics['specifics']);
			$this->_view['variation_specifics'] = $variation_specifics;
		}
		$pictures = Online_Ebay_Listing_Picture::getListingPicture($listing['id']);
		$details = Online_Ebay_Listing::getEbyDetails($site_id);
		$this->_view['country'] = Country::find()->asArray()->getAll();
		$this->_view['listing'] = $listing;
		$this->_view['currency'] = Currency::find('id=?', $listing['currency_id'])->asArray()->getOne();;
		$this->_view['listing_type'] = $listing_type;
		$this->_view['store_categories'] = $store_categories['categories'];
		$this->_view['features'] = $features['features'];
		$this->_view['specifics'] = $specifics['specifics'];
		$this->_view['item_specifics'] = $item_specifics;
		$this->_view['item'] = $item;
		$this->_view['pictures'] = $pictures;
		$this->_view['dispatch'] = $details['details']['dispatch'];
		$this->_view['shipping_service'] = $details['details']['shipping_service'];
		$this->_view['listing_shipping'] = Online_Ebay_Listing_Shipping::getListingShipping($listing['id']);
		$this->_view['shipping_location'] = $details['details']['shipping_location'];
		$this->_view['shipping_location_json'] = json_encode($details['details']['shipping_location']);
		$this->_view['return_policy'] = $details['details']['return_policy'];
	}
	
	function actionCopySave()
	{
		$this->_view['title'] = '复制（保存）';
		if ($this->_context->isPOST())
		{
			$mapping = Shop_User_Mapping::checkMapping($_POST['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$listing = Online_Ebay_Listing::assembleListingByPost($_POST);
				$create_result = Online_Ebay_Listing::create($listing);
				return $this->_redirectMessage('', $create_result['message'], url('Online::EbayListing/LibraryList'), $create_result['ack']);
			}
			else
			{
				return $this->_redirectMessage('复制失败', $mapping['message'], $_SERVER['HTTP_REFERER'], $mapping['ack']);
			}
		}
	}
	
	function actionDelete()
	{
		$this->_view['title'] = '删除';
		$ids = explode(',', $_REQUEST['ids']);
		$message = array();
		foreach ($ids as $key => $id)
		{
			$listing_in_db = Online_Ebay_Listing::find('id=?', $id)->asArray()->getOne();
			if ($listing_in_db)
			{
				$mapping = Shop_User_Mapping::checkMapping($listing_in_db['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					$delete_result = Online_Ebay_Listing::delete($id);
				    if ($delete_result['ack'] != SUCCESS)
					{
						$message[] = 'No.' . ($key + 1) . ': ' . $delete_result['message'];
					}
				}
				else
				{
					$message[] = 'No.' . ($key + 1) . ': ' . $mapping['message'];
				}
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ': listing不存在';
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('部分删除失败', implode('; ', $message), $_SERVER['HTTP_REFERER'], PARTIAL_FAILURE);
		}
		else
		{
			return $this->_redirectMessage('删除成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionOnlineList()
	{
		$this->_view['title'] = '上架列表';
		$this->_view['shop'] = Shop::getPlatformShopToArray('ebay');
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->asArray()->getAll();
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['lib_flag'] = Q::ini('custom_flag/ebay_listing_lib_flag/unflag/value');
		$search_result = Online_Ebay_Listing::search($condition, $cp, $ps, 'online_ebay_listing.id desc');
		$page = new Helper_BSS_Page($search_result['pagination'], url('Online::EbayListing/OnlineList', $condition));
		$this->_view['page'] = $page->getPage();
		$listing = $search_result['data'];
		foreach ($listing as &$l)
		{
			Online_Ebay_Listing_Extend::getListingExtend($l);			
		}
		unset($l);
		Online_Ebay_Listing_Picture::getListingsGalleryPicture($listing);
		$this->_view['listing'] = $listing;
	}
	
	function actionLibraryList()
	{
		$this->_view['title'] = '资料库列表';	
		$this->_view['shop'] = Shop::getPlatformShopToArray('ebay');
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->asArray()->getAll();
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['lib_flag'] = Q::ini('custom_flag/ebay_listing_lib_flag/flag/value');
		$search_result = Online_Ebay_Listing::search($condition, $cp, $ps, 'online_ebay_listing.id desc');
		$page = new Helper_BSS_Page($search_result['pagination'], url('Online::EbayListing/LibraryList', $condition));
		$this->_view['page'] = $page->getPage();
		$listing = $search_result['data'];
		foreach ($listing as &$l)
		{
			Online_Ebay_Listing_Extend::getListingExtend($l);			
		}
		unset($l);
		Online_Ebay_Listing_Picture::getListingsGalleryPicture($listing);
		$this->_view['listing'] = $listing;
	}
	
	function actionItemList()
	{
		$this->_view['title'] = 'SKU列表';
		$this->_view['shop'] = Shop::getPlatformShopToArray('ebay');
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['online_flag'] = 1;
		$order_by = '';
		$url_arr = Helper_BSS_Normal::buildCondition();
		if (isset($url_arr['sort_by']) && isset($url_arr['sort_order']))
		{
			$order_by = $url_arr['sort_by'] . ' ' . $url_arr['sort_order'];
		}
		$search_result = Online_Ebay_Listing_Item::search($condition, $cp, $ps, $order_by);
		$result = array();
		foreach ($search_result['data'] as $sr)
		{
			$product = Product_Warehouse::find('product_basic.number=? and product_warehouse.warehouse_id=1', $sr['sku'])
					->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
					->setColumns('product_warehouse.available_quantity, product_warehouse.sales_status, product_warehouse.purchase_status')
					->asArray()->getOne();
			$result[$sr['id']] = $sr;	
			if ( ! empty($product))
			{
				$result[$sr['id']]['available_quantity'] = $product['available_quantity'];
				$result[$sr['id']]['sales_status'] = $product['sales_status'];
				$result[$sr['id']]['purchase_status'] = $product['purchase_status'];
			}
			$extend = Online_Ebay_Listing_Extend::find('online_ebay_listing_id=?', $sr['online_ebay_listing_id'])->asArray()->getOne();
			$result[$sr['id']]['view_url'] = $extend['view_url'];
		}
		$page = new Helper_BSS_Page($search_result['pagination'], url('Online::EbayListing/ItemList', $condition));
		$this->_view['page'] = $page->getPage();
		unset($url_arr['sort_by']);
		unset($url_arr['sort_order']);
		$this->_view['url'] = url('Online::EbayListing/ItemList', $url_arr);
		$this->_view['item'] = $result;
	}
	
	function actionBrowseCategoriesAjax()
	{
		$this->_view['title'] = '浏览ebay分类';
		$site = ($_GET['site'] == 'US') ? array('US', 'Motors') :  array($_GET['site']);
		$level = $_GET['level'];
		$parent_id = $_GET['parent_id'];
		if ($parent_id)
		{
			$where = ' and parent_id=' . $parent_id;
		}
		else
		{
			$where = '';
		}
		$categories = Online_Ebay_Listing_Categories::find('site in (?) and level=?' . $where, $site, $level)->order('name asc')->asArray()->getAll();
		echo json_encode($categories);exit;
	}
	
	function actionSearchCategoryAjax()
	{
		$this->_view['title'] = '搜索ebay分类';
		$leaf = Q::ini('custom_flag/online_ebay_listing_categories_leaf/leaf/value');
		$site = ($_REQUEST['site'] == 'US') ? array('US', 'Motors') : array($_REQUEST['site']);
		$categories = Online_Ebay_Listing_Categories::find('site in (?) and (name like ? or id=?) and leaf=?', $site, '%' . $_REQUEST['q'] . '%', $_REQUEST['q'], $leaf)->limit(0, 20)->asArray()->getAll();
		$result = array();
		foreach ($categories as $c)
		{
			$ancestor = Online_Ebay_Listing_Categories::getAncestorById($c['id'], $site);
			$show = $c['id'] . ': ';
			$name = '';
			foreach ($ancestor as $a)
			{
				$show .= $a['name'];
				$name .= $a['name'];
				if ($a['leaf'] != $leaf)
				{
					$show .= ' > ';
					$name .= ':';
				}
			}
			$result[] = array('id' => $c['id'], '0' => $show, 'name' => $name);
		}
		echo json_encode($result);exit;
	}
	
	function actionGetInfoByCategoryAjax()
	{
		$this->_view['title'] = '获取ebay分类相关信息';
		$site = $_GET['site'];
		$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $site, 'site_id');
		$shop_id = $_GET['shop_id'];
		$category_id = $_GET['category_id'];
		$features = Online_Ebay_Listing::getCategoryFeatures($shop_id, $site_id, $category_id);
		$specifics = Online_Ebay_Listing::getCategorySpecifics($shop_id, $site_id, $category_id);
		echo json_encode(array('features' => $features, 'specifics' => $specifics));exit;
	}
	
	function actionGetInfoByShopAndSiteAjax()
	{
		$this->_view['title'] = '获取店铺和站点相关信息';
		$site = $_GET['site'];
		$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $site, 'site_id');
		$shop_id = $_GET['shop_id'];
		$store_categories = Online_Ebay_Listing::getStoreCategories($shop_id, $site_id);
		echo json_encode(array('store_categories' => $store_categories['categories']));exit;
	}
	
	function actionGetInfoBySiteAjax()
	{
		$this->_view['title'] = '获取站点相关信息';
		$site = $_GET['site'];
		$currency_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $site, 'currency_id');
		$currency = Currency::find('id=?', $currency_id)->asArray()->getOne();
		$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $site, 'site_id');
		$details = Online_Ebay_Listing::getEbyDetails($site_id);
		echo json_encode(array('currency' => $currency, 'dispatch' => $details['details']['dispatch'], 'shipping_service' => $details['details']['shipping_service'], 'shipping_location' => $details['details']['shipping_location'], 'return_policy' => $details['details']['return_policy']));exit;
	}
	
	function actionVerifyAjax()
	{
		$this->_view['title'] = '信息验证';
		if ($this->_context->isPOST())
		{
			$listing = Online_Ebay_Listing::assembleListingByPost($_POST);
			if (isset($listing['id']))
			{
				$in_db = Online_Ebay_Listing::find('id=?', $listing['id'])->asArray()->getOne();
				$listing['site'] = $in_db['site'];
				$listing['shop_id'] = $in_db['shop_id'];
				$listing['currency_id'] = $in_db['currency_id'];
				$listing['payment_method'] = $in_db['payment_method'];
				$listing['payment_address'] = $in_db['payment_address'];
			}
			if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
			{
				$verify_result = Online_Ebay_Listing::verifyAddFixedPriceItem($listing);
			}
			else
			{
				$verify_result = Online_Ebay_Listing::verifyAddItem($listing);
			}
			echo json_encode($verify_result);exit;
		}
	}
	
	function actionUpdateListing()
	{
		$this->_view['title'] = '强制更新Listing信息';
		$listing_in_db = Online_Ebay_Listing::find('id=?', $_GET['id'])->asArray()->getOne();
		if ($listing_in_db)
		{
			$mapping = Shop_User_Mapping::checkMapping($listing_in_db['shop_id']);
			if ($mapping['ack'] == SUCCESS)
			{
				$update_result = Online_Ebay_Listing::updateListing($_GET['id'], true);
				return $this->_redirectMessage('', $update_result['message'], $_SERVER['HTTP_REFERER'], $update_result['ack']);
			}
			else
			{
				return $this->_redirectMessage('更新失败', $mapping['message'], $_SERVER['HTTP_REFERER'], $mapping['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('更新失败', '该listing不存在', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionPush()
	{
		$this->_view['title'] = '推送';
		$ids = explode(',', $_REQUEST['ids']);
		$message = array();
		foreach ($ids as $key => $id)
		{
			$listing_in_db = Online_Ebay_Listing::find('id=?', $id)->asArray()->getOne();
			if ($listing_in_db)
			{
				$mapping = Shop_User_Mapping::checkMapping($listing_in_db['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					if ($listing_in_db['item_id'])
					{
						$push_result = Online_Ebay_Listing::pushRevise($id);
					}
					else
					{
						$push_result = Online_Ebay_Listing::pushAdd($id, Q::ini('custom_flag/ebay_listing_push_type/manual/value'));
					}
					if ($push_result['ack'] == FAILURE)
					{
						$message[] = 'No.' . ($key + 1) . ': ' . $push_result['message'];
					}
				}
				else
				{
					$message[] = 'No.' . ($key + 1) . ': ' . $mapping['message'];
				}
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ': listing不存在';
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('部分失败', implode("\n", $message), $_SERVER['HTTP_REFERER'], PARTIAL_FAILURE);
		}
		else
		{
			return $this->_redirectMessage('推送成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionRelist()
	{
		$this->_view['title'] = '重新刊登';
		$ids = explode(',', $_REQUEST['ids']);
		$message = array();
		foreach ($ids as $key => $id)
		{
			$listing_in_db = Online_Ebay_Listing::find('id=?', $id)->asArray()->getOne();
			if ($listing_in_db)
			{
				$mapping = Shop_User_Mapping::checkMapping($listing_in_db['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					$relist_result = Online_Ebay_Listing::relist($id);
					if ($relist_result['ack'] != SUCCESS)
					{
						$message[] = 'No.' . ($key + 1) . ': ' . $relist_result['message'];
					}
				}
				else
				{
					$message[] = 'No.' . ($key + 1) . ': ' . $mapping['message'];
				}
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ': listing不存在';
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('部分重新刊登失败', implode('; ', $message), $_SERVER['HTTP_REFERER'], PARTIAL_FAILURE);
		}
		else
		{
			return $this->_redirectMessage('重新刊登成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionEnd()
	{
		$this->_view['title'] = '下架';
		$ids = explode(',', $_REQUEST['ids']);
		$reason = $_POST['param1'];
		$message = array();
		foreach ($ids as $id)
		{
			$listing_in_db = Online_Ebay_Listing::find('id=?', $id)->asArray()->getOne();
			if ($listing_in_db)
			{
				$mapping = Shop_User_Mapping::checkMapping($listing_in_db['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					$end_result = Online_Ebay_Listing::end($id, $reason);
					if ($end_result['ack'] != SUCCESS)
					{
						$message[] = 'No.' . ($key + 1) . ': ' . $end_result['message'];
					}
				}
				else
				{
					$message[] = 'No.' . ($key + 1) . ': ' . $mapping['message'];
				}
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ': listing不存在';
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('部分下架失败', implode('; ', $message), $_SERVER['HTTP_REFERER'], PARTIAL_FAILURE);
		}
		else
		{
			return $this->_redirectMessage('下架成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionReviseInventory()
	{
		$this->_view['title'] = '修改数量和价格';
		$item = Online_Ebay_Listing_Item::find('online_ebay_listing_item.id in (?)', explode(',', $_GET['ids']))
			->joinLeft('online_ebay_listing', 'item_id', 'online_ebay_listing.id=online_ebay_listing_item.online_ebay_listing_id')
			->joinLeft('shop', 'name as shop_name', 'shop.id=online_ebay_listing.shop_id')
			->joinLeft('currency', 'symbol as currency_symbol', 'currency.id=online_ebay_listing.currency_id')
			->asArray()->getAll();
		$listing = array();
		foreach ($item as $i)
		{
			$listing[$i['item_id']][] = $i;
		}
		$this->_view['listing'] = $listing;
	}
	
	function actionReviseInventorySave()
	{
		$this->_view['title'] = '修改数量和价格（保存）';
		if ($this->_context->isPOST())
		{
			$message = array();
			foreach ($_POST['listing'] as $l)
			{
				$listing = Online_Ebay_Listing::find('id=?', $l['id'])->asArray()->getOne();
				$mapping = Shop_User_Mapping::checkMapping($listing['shop_id']);
				if ($mapping['ack'] != SUCCESS)
				{
					$message[] = 'Item ID ' . $listing['item_id'] . ': ' . $mapping['message'];
					continue;
				}
				if ($listing['lib_flag'] == Q::ini('ebay_listing_lib_flag/flag/value'))
				{
					continue;
				}
				$listing['item'] = $l['item'];
				$revise_result = Online_Ebay_Listing::reviseInventoryAndPrice($listing);
				if ($revise_result['ack'] != SUCCESS)
				{
					$message[] = 'Item ID ' . $listing['item_id'] .  ':' . $revise_result['message'];
				}
			}
			if ($message)
			{
				return $this->_redirectMessage('部分失败', implode(';', $message), $_SERVER['HTTP_REFERER'], PARTIAL_FAILURE);
			}
			else
			{
				return $this->_redirectMessage('修改成功', '正在返回列表', $_SERVER['HTTP_REFERER'], SUCCESS);
			}
		}
	}
	
	function actionKeepQuantity()
	{
		$this->_view['title'] = '维持数量';
		$item = Online_Ebay_Listing_Item::find('online_ebay_listing_item.id in (?) and online_ebay_listing.listing_type=? and online_ebay_listing.listing_duration=? and online_ebay_listing.sell_status=?', explode(',', $_GET['ids']), 'FixedPriceItem', 'GTC', Q::ini('custom_flag/online_ebay_listing_sell_status/active/value'))
			->joinLeft('online_ebay_listing', 'item_id', 'online_ebay_listing.id=online_ebay_listing_item.online_ebay_listing_id')
			->joinLeft('shop', 'name as shop_name', 'shop.id=online_ebay_listing.shop_id')
			->joinLeft('currency', 'symbol as currency_symbol', 'currency.id=online_ebay_listing.currency_id')
			->asArray()->getAll();
		$listing = array();
		foreach ($item as $i)
		{
			$listing[$i['item_id']][] = $i;
		}
		$this->_view['listing'] = $listing;
	}
	
	function actionKeepQuantitySave()
	{
		$this->_view['title'] = '维持数量（保存）';
		if ($this->_context->isPOST())
		{
			$item = array();
			foreach ($_POST['item'] as $key => $i)
			{
				$db = Online_Ebay_Listing_Item::find('online_ebay_listing_item.id=?', $key)->joinLeft('online_ebay_listing', 'shop_id', 'online_ebay_listing.id=online_ebay_listing_item.online_ebay_listing_id')->asArray()->getOne();
				$mapping = Shop_User_Mapping::checkMapping($db['shop_id']);
				if ($mapping['ack'] == SUCCESS)
				{
					$item[] = array(
						'id' => $key,
						'keep_quantity' => $i['keep_quantity'],
						'keep_quantity_flag' => isset($i['keep_quantity_flag']) ? Q::ini('custom_flag/online_ebay_listing_item_keep_quantity_flag/keep/value') : Q::ini('custom_flag/online_ebay_listing_item_keep_quantity_flag/not_keep/value')
					);
				}
				else
				{
					return $this->_redirectMessage('有店铺权限不足', '正在返回', $_SERVER['HTTP_REFERER'], FAILURE);
				}
			}
			$edit_result = Online_Ebay_Listing_Item::keepQuantityEdit($item);
			return $this->_redirectMessage($edit_result['message'], '正在返回', $_SERVER['HTTP_REFERER'], $edit_result['ack']);
		}
	}
	
	function actionRefreshStoreCategories()
	{
		$this->_view['title'] = '刷新店铺分类';
		$this->_view['shop'] = Shop::getPlatformShopToArray('ebay');
	}
	
	function actionRefreshStoreCategoriesSave()
	{
		$this->_view['title'] = '刷新店铺分类（保存）';
		if (isset($_POST['shop']) && isset($_POST['site']))
		{	
			QDB::getConn()->execute('update online_ebay_listing_api_cache set filename =\'\' where shop_id =' . $_POST['shop'] . ' and site_id =' . Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $_POST['site'], 'site_id'));
			return $this->_redirectMessage('刷新成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
		else
		{
			return $this->_redirectMessage('没有店铺和站点的信息', '正在返回', url('Online::EbayListing/refreshstorecategories'), FAILURE);
		}
	}
	
	function actionProductTraceList()
	{
		$this->_view['title'] = '产品上架跟踪查询表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$product_categories = Product_Categories::getCategoriesTree();
		$this->_view['product_categories'] = json_encode($product_categories);
		$condition = Helper_BSS_Normal::buildCondition();
		$result = Online_Ebay_Listing::GetProductTraceData($condition, $cp, $ps);
		$page = new Helper_BSS_Page($result['pagination'], url('Online::EbayListing/ProductTraceList', $condition));
		$this->_view['page'] = $page->getPage();
		Helper_BSS_Normal::getProductImgUrl($result['data']);
		$this->_view['item'] = $result['data'];
		$this->_view['url_arr'] = json_encode($condition);
		$this->_view['url'] = url('Online::EbayListing/ProductTraceList', $condition);
	}
	
	function actionProductTraceListExport()
	{
		$this->_view['title'] = '产品上架跟踪查询表导出';
		$condition = json_decode($_REQUEST['url_arr'], 1);
		$result = Online_Ebay_Listing::GetProductTraceData($condition, 1, 1000);
		Helper_BSS_XLS::ProductTraceListExport($result['data']);
	}
	
	function actionProductTraceDetail()
	{
		$this->_view['title'] = '产品上架跟踪查询表（详细）';
		$url_arr = Helper_BSS_Normal::buildCondition();
		if ($url_arr)
		{
			$online_ebay_listing_item = Online_Ebay_Listing_Item::find('online_ebay_listing_item.product_basic_id =?', $url_arr['id'])
				->joinLeft('online_ebay_listing', 'online_ebay_listing.*', 'online_ebay_listing_item.online_ebay_listing_id=online_ebay_listing.id')
				->joinLeft('online_ebay_listing_extend', 'online_ebay_listing_extend.*', 'online_ebay_listing_item.online_ebay_listing_id=online_ebay_listing_extend.online_ebay_listing_id')
				->joinLeft('shop', 'name', 'online_ebay_listing.shop_id=shop.id')
				->joinLeft('currency', 'currency.code as currency_code', 'currency.id=online_ebay_listing.currency_id')
				->where('online_ebay_listing.end_time >\''. date("Y-m-d H:i:s") . '\' and online_ebay_listing.sell_status=' . Q::ini('custom_flag/online_ebay_listing_sell_status/active/value') . ' and online_ebay_listing.listing_type like "' . Q::ini('custom_flag/online_ebay_listing_type/fixedpriceitem/value') . '" ')
				->order('shop.name')
				->asArray()->getAll();
			$this->_view['item'] = $online_ebay_listing_item;
		}
		else
		{
			return $this->_redirect(url('Online::EbayListing/ProductTraceList'));
		}
	}
	
	function actionSetSchedule()
	{
		$this->_view['title'] = '设置schedule';
		$ids = explode(',', $_REQUEST['ids']);
		foreach ($ids as $k => $id)
		{
			$listing = Online_Ebay_Listing::find('id=?', $id)->getOne();
			if ($listing['id'])
			{
				if ($_REQUEST['date'])
				{
					$listing->schedule_flag = Q::ini('custom_flag/online_ebay_listing_schedule_flag/set/value');
					$listing->schedule_next_time = date('Y-m-d H:i:s', strtotime($_REQUEST['date'] . ' ' . $_REQUEST['hour'] . ':' . $_REQUEST['minute'] . ':00') + $_REQUEST['interval_minute']*$k*60);
					$listing->schedule_time_show_timezone = $_REQUEST['timezone'];
					if (isset($_REQUEST['schedule_repeat']) && $_REQUEST['schedule_repeat_step'])
					{
						$listing->schedule_repeat = Q::ini('custom_flag/online_ebay_listing_schedule_repeat/repeat/value');
						$listing->schedule_repeat_step = $_REQUEST['schedule_repeat_step'];
					}
					else
					{
						$listing->schedule_repeat = Q::ini('custom_flag/online_ebay_listing_schedule_repeat/no_repeat/value');
						$listing->schedule_repeat_step = '';
					}
				}
				else
				{
					$listing->schedule_flag = Q::ini('custom_flag/online_ebay_listing_schedule_flag/not_set/value');
					$listing->schedule_time_show_timezone= '';
					$listing->schedule_next_time = '';
					$listing->schedule_repeat = Q::ini('custom_flag/online_ebay_listing_schedule_repeat/no_repeat/value');
					$listing->schedule_repeat_step = '';
				}
				$listing->save(); 
			}
		}
		return $this->_redirectMessage('设置成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
	}
	
	function actionScheduleWrongDetail()
	{
		$this->_view['title'] = 'Schedule详情';
		if (isset($_REQUEST['id']) && $_REQUEST['id'])
		{
			$log = Online_Ebay_Listing_Log::find('online_ebay_listing_id=?', $_REQUEST['id'])->asArray()->getAll();
			if ($log)
			{
				$this->_view['log'] = $log;
			}
			else
			{
				return $this->_redirectMessage('不存在该listing日志', '正在返回', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
	}
	
	function actionFolderList()
	{
		$this->_view['title'] = 'Folder列表';
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->order('sort')->asArray()->getAll();
	}
	
	function actionFolderCreate()
	{
		$this->_view['title'] = '创建文件夹';
		$folder = Online_Ebay_Listing_Folder::find('name=?', trim($_POST['newname']))->getOne();
		if ( ! $folder['id'])
		{
			$new_folder = array();
			$new_folder['name'] = trim($_POST['newname']);
			Online_Ebay_Listing_Folder::create($new_folder);
		}
		else
		{
			return $this->_redirectMessage('创建失败,文件夹名字已存在', '正在返回', $_SERVER['HTTP_REFERER'], FAILURE);
		}
		return $this->_redirectMessage('创建成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
	}
	
	function actionFolderEditSave()
	{
		$this->_view['title'] = '文件夹编辑（保存）';
		if ($this->_context->isPOST())
		{
			$message = '';
			foreach ($_POST['folder'] as $f)
			{
				$folder = array('id' => $f['id'], 'name' => trim($f['name']), 'sort' => trim($f['sort']));
				$result = Online_Ebay_Listing_Folder::edit($folder);
				if ($result['ack'] != SUCCESS)
				{
					$message .= $result['message'] . "\n";
				}
			}
			if ($message)
			{
				return $this->_redirectMessage('保存失败', $message, $_SERVER['HTTP_REFERER'], SUCCESS);
			}
			else
			{
				return $this->_redirectMessage('保存成功', '正在返回..',  url('Online::EbayListing/FolderList'), FAILURE);
			}
		}
	}
	
	function actionFolderDelete()
	{
		$this->_view['title'] = '文件夹删除';
		$ids = explode(',', $_REQUEST['ids']);
		$message = array();
		foreach ($ids as $key => $id)
		{
			$folder = Online_Ebay_Listing_Folder::find('id=?', $id)->asArray()->getOne();
			if ($folder)
			{
				Online_Ebay_Listing_Folder::delete($id);
			}
			else
			{
				$message[] = 'No.' . ($key + 1) . ': folder不存在';
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('部分删除失败', implode('; ', $message), $_SERVER['HTTP_REFERER'], PARTIAL_FAILURE);
		}
		else
		{
			return $this->_redirectMessage('删除成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionMoveToFolder()
	{
		$this->_view['title'] = '文件夹移动';
		$ids = explode(',', $_REQUEST['ids']);
		if (isset($_POST['folder_id']) && $_POST['folder_id'])
		{
			foreach ($ids as $id)
			{
				$listing = Online_Ebay_Listing::find('id=?', $id)->getOne();
				if ($listing['id'])
				{
					$listing->online_ebay_listing_folder_id = $_POST['folder_id'];
					$listing->save();
				}
			}
			return $this->_redirectMessage('移动成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionMultiCopy()
	{
		$this->_view['title'] = '批量复制';
		$shop = Shop_User_Mapping::getShopByPlatform();
		$this->_view['folder'] = Online_Ebay_Listing_Folder::find()->order('sort')->asArray()->getAll();
		if (isset($_GET['id']) && $_GET['id'])
		{
			if ($_GET['shop_ids'])
			{
				$shop_ids = explode(',', $_GET['shop_ids']);
				$this->_view['shop_ids'] = $shop_ids;
				if ($_GET['folder_id'])
				{
					$this->_view['folder_id'] = $_GET['folder_id'];
				}				
			}
			$listing = Online_Ebay_Listing::find('id=?', $_GET['id'])->asArray()->getOne();
			$include_shop = false;
			foreach ($shop as $s)
			{
				if ($s['id'] == $listing['shop_id'])
				{
					$include_shop = true;
				}
			}
			if ( ! $include_shop)
			{
				$current_shop = Shop::find('id=?', $listing['shop_id'])->asArray()->getOne();
				array_unshift($shop, $current_shop);
			}
			$this->_view['shop'] = $shop;
			Online_Ebay_Listing_Extend::getListingExtend($listing);
			$this->_view['listing'] = $listing;
		}
	}
	
	function actionMultiCopySave()
	{
		$this->_view['title'] = '批量复制（保存）';
		$message = '';
		$n = 1;
		foreach ($_POST['listing'] as $l)
		{ 
			if ($l['shop_id'])
			{
				$l['desc_text'] = $_POST['desc_text'];
				Online_Ebay_Listing::copy($l, $_POST['id']);
			}
			else
			{
				$message = $n . "条listing没有指定shop\n";
				$n = $n + 1;
			}
		}
		if ($message)
		{
			return $this->_redirectMessage('复制部分失败', $message, url('Online::EbayListing/LibraryList'), FAILURE);
		}
		else
		{
			return $this->_redirectMessage('复制成功', '', url('Online::EbayListing/LibraryList'), SUCCESS);
		}
	}
	
	function actionGetTemplateByShopAjax()
	{
		$this->_view['title'] = '根据店铺获得模板（AJAX）';
		$template = QDB::getConn()->execute('select id,name from ebay_template where shop_id = ' . $_REQUEST['shop_id'])->fetchAll();
		echo json_encode($template);exit;
	}
}
